package logic

import (
	"context"
	"fmt"
	"housing/model/mysql"
	"housing/model/redis"
	"housing/pkg"

	"housing/housingrpc/housingrpc"
	"housing/housingrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserregisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserregisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserregisterLogic {
	return &UserregisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserregisterLogic) Userregister(in *housingrpc.UserregisterRequest) (*housingrpc.UserregisterResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Captacharegister" + in.Phone)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("验证码输入错误，请从新输入")
	}
	cmd := redis.Client.Get("sendSmsregister" + in.Phone)
	if cmd.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信验证码输入错误，请从新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("账号已存在，请重新输入")
	}

	user := mysql.User{
		Phone:    in.Phone,
		Password: pkg.Md5Password(in.Password),
	}

	mysql.DB.Debug().Create(&user)
	redis.Client.Del("Captacharegister" + in.Phone)
	redis.Client.Del("sendSmsregister" + in.Phone)
	return &housingrpc.UserregisterResponse{Id: int64(user.ID)}, nil
}
